package com.ysqcould.common.utils.okhttp;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jcd
 * 管理cookie
 */
@Slf4j
public class MyCookieStore implements CookieJar {
    /**打印日志用**/
    private static volatile boolean debug = false;

    /**登录后拿到的token**/
    private static String TOKEN = "";

    /**管理cookie**/
    private static ConcurrentHashMap<String, ConcurrentHashMap<String, Cookie>> cookieStore = new ConcurrentHashMap<>();

    /**token资源文件位置**/
    public static final String TOKEN_FILE_PATH = "/store/token.txt";

    /**cookie资源文件位置**/
    public static final String COOKIE_FILE_PATH = "/store/cookie.txt";


    @Override
    public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
        log.info("-----保存cookie");

        //保存cookie
        log.info("httpUrl host: " + httpUrl.host());
        ConcurrentHashMap<String, Cookie> cookieMap = cookieStore.get(httpUrl.host());
        if (cookieMap == null) {
            cookieMap = new ConcurrentHashMap<>();
            cookieStore.put(httpUrl.host(), cookieMap);
        }
        for (Cookie cookie : list) {
            cookieMap.put(cookie.name(), cookie);
        }

        if (list != null && list.size() > 0) {
            //存到本地，需要自己写持久化的实现，可用redis，或本地
        }

        log.info("-----保存到cookie：" + cookieStore.toString());
        log.info("------------------------：");
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl httpUrl) {
        log.info("---加载 cookie");
        List<Cookie> cookies = new ArrayList<>();
        Map<String, Cookie> cookieMap = cookieStore.get(httpUrl.host());
        if (cookieMap != null) {
            cookieMap.forEach((name, cookie)->{
                log.info("--cookie:" + name + "=" + cookie.value());
                cookies.add(cookie);
            });
        }
        log.info("---load cookie");
        return cookies;
    }
    public static void setToken(String token) {
        TOKEN = token;
    }

    public static String getToken() {
        return TOKEN;
    }
}
